package com.example.rae.controller;

import org.redisson.Redisson;
import org.redisson.RedissonRedLock;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class IndexController {

    @Autowired
    private Redisson redisson;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/deduckStock")
    public String deduckStock() {

        String lockKey = "product_001";
        String clientId = UUID.randomUUID().toString();
        RLock redissonLock = redisson.getLock(lockKey);
        // 出现异常，导致死锁，添加try-finally
        try {
            // redis实现分布式锁
//        Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, "zhang"); // jedis.setnx(key,value)
            // 如果服务宕机了，造成死锁,添加过期时间
//        stringRedisTemplate.expire(lockKey, 10, TimeUnit.SECONDS);
//            Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, "zhang", 10, TimeUnit.SECONDS);
//            // 可以通过续命，添加定时任务来延长超时时间
//            if (!result) {
//                return "error";
//            }
            redissonLock.lock();
            Integer stock = Integer.valueOf(stringRedisTemplate.opsForValue().get("stock"));
            if (stock > 0) {
                Integer realStock = stock - 1;
                stringRedisTemplate.opsForValue().set("stock", String.valueOf(realStock));
                System.out.println("扣减库存成功，剩余库存：" + realStock);
            } else {
                System.out.println("扣减库存成功，库存不足");
            }
        } finally {
            redissonLock.unlock();
//            // 添加uuid，自己的锁，只能由自己释放
//            if (clientId.equals(stringRedisTemplate.opsForValue().get(lockKey))) {
//                stringRedisTemplate.delete(lockKey);
//            }
        }

        return "end";
    }

    @RequestMapping("/readLock")
    public String readLock() {
        String lockKey = "product_001";
        // 这里需要自己实例化不同redis实例的redission客户端连接，这是伪代码用一个 redission客户端简化了
        RLock lock1 = redisson.getLock(lockKey);
        RLock lock2 = redisson.getLock(lockKey);
        RLock lock3 = redisson.getLock(lockKey);

        /**
         * 根据多个RLock对象构建RedissonRedLock(最核心的代码)
         */
        RedissonRedLock redissonRedLock = new RedissonRedLock(lock1, lock2, lock3);
        try {
            /**
             * waitTime尝试获取锁最大等待时间，超过这个值，则认为获取锁失败
             * leaseTime 锁持有时间，超过这个时间锁会自动失败
             */
            boolean res = redissonRedLock.tryLock(10, 30, TimeUnit.SECONDS);
            if (res) {
                // 成功获取锁，执行业务逻辑
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 无论如何，最后都要解锁
            redissonRedLock.unlock();
        }
        return "end";
    }
}
